package persistence;

import org.hibernate.*;
import org.hibernate.usertype.*;
import org.hibernate.util.*;

import java.io.*;
import java.sql.*;
import java.math.*;
import java.util.*;
import hello.*;

public class StringEnumUserType implements EnhancedUserType,ParameterizedType
{
	private Class<Enum> enumClass;
	
	public void setParameterValues(Properties parameters){
		String enumClassName=parameters.getProperty("enumClassname");
		try{
			enumClass=ReflectHelper.classForName(enumClassName);
		}catch(ClassNotFoundException cnfe){
			throw new HibernateException("Enum class not found",cnfe);
		}
	}
	
	
	
	public int[] sqlTypes()
	{
		out("in sqlTypes()");
		return new int[]{ Hibernate.STRING.sqlType()};
	}
	
	public Class returnedClass()
	{
		return enumClass;
	}
	
	public boolean isMutable()
	{
		return false;
	}
	
	public Object deepCopy(Object value)
	{
		return value;
	}
	
	public Serializable disassemble(Object value)
	{
		return (Serializable)value;
	}
	
	public Object assemble(Serializable cached,Object owner)
	{
		return cached;
	}
	
	public Object replace(Object original,Object target,Object owner)
	{
		return original;
	}
	
	public boolean equals(Object x,Object y)
	{
		if(x == y)
			return true;
		if(x==null || y==null)
			return false;
		return x.equals(y);
	}
	
	public int hashCode(Object x)
	{
		return x.hashCode();
	}
	
	public Object fromXMLString(String xmlValue){
		return Enum.valueOf(enumClass,xmlValue);
	}
	
	public String objectToSQLString(Object obj){
		return '\''+((Enum)obj).name()+'\'';
	}
	
	public String toXMLString(Object obj){
		return ((Enum)obj).name();
	}
	
	public Object nullSafeGet(ResultSet resultSet,String[] names,Object owner)throws SQLException
	{//how to construct user type
		out("enter nullSafeGet:"+Arrays.asList(names)+"\t"+owner.getClass().getName());
		String name =resultSet.getString(names[0]);
		return resultSet.wasNull() ? null : Enum.valueOf(enumClass,name);
	}
	
	public void nullSafeSet(PreparedStatement statement,Object value,int index)throws HibernateException,SQLException
	{//how to persist user type
		if(value==null)
		{
			statement.setNull(index,Hibernate.STRING.sqlType());
			out("enter nullSafeSet: set null to parameter:"+index);
		}else
		{
			String v=((Enum)value).name();
			statement.setString(index,v);
			//String st=null;st.length();
			out("enter nullSafeSet: bind "+v+" to parameter:"+index);
			
		}
	}
	
	void out(Object obj)
	{
		System.out.println(this.getClass().getName()+"===>"+obj.toString());
	}
}